﻿using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace ExpertNewsRotator2
{
    public class ImageUploaderEditor : UserControl, IFieldEditor
    {
        protected DropDownList DdlLookupFieldTargetList;
        private ImageUploader fldPAImageUploader;
        protected Label LabelLookupFieldTargetListTitle;
        protected Label lblWidth;
        protected TextBox txtWidth;

        public void InitializeWithField(SPField field)
        {
            this.fldPAImageUploader = field as ImageUploader;
            if (!this.Page.IsPostBack)
            {
                this.PopulatePageTypes();
                if (field != null)
                {
                    this.DdlLookupFieldTargetList.SelectedValue = this.fldPAImageUploader.MyCustomProperty;
                    this.DdlLookupFieldTargetList.Visible = true;
                    this.txtWidth.Text = this.fldPAImageUploader.PAWidth;
                    this.txtWidth.Visible = true;
                }
                else
                {
                    this.DdlLookupFieldTargetList.SelectedIndex = 1;
                    this.DdlLookupFieldTargetList.Visible = true;
                    this.txtWidth.Text = "270";
                    this.txtWidth.Visible = true;
                }
            }
        }

        public void OnSaveChange(SPField field, bool bNewField)
        {
            ImageUploader uploader = (ImageUploader)field;
            uploader.IsNew = bNewField;
            uploader.MyCustomProperty = this.DdlLookupFieldTargetList.SelectedValue;
            uploader.PAWidth = this.txtWidth.Text;
        }

        public void PopulatePageTypes()
        {
            this.DdlLookupFieldTargetList.Items.Clear();
            SPSite site = new SPSite(SPContext.Current.Web.Url);
            SPUserToken userToken = SPContext.Current.Site.SystemAccount.UserToken;
            using (SPSite site2 = new SPSite(SPContext.Current.Web.Url, userToken))
            {
                using (SPWeb web = site2.OpenWeb())
                {
                    SPListCollection lists = web.Lists;
                    foreach (SPList list in lists)
                    {
                        if ((list.BaseTemplate == SPListTemplateType.DocumentLibrary) || (list.BaseTemplate == SPListTemplateType.PictureLibrary))
                        {
                            this.DdlLookupFieldTargetList.Items.Add(list.Title);
                        }
                    }
                }
            }
        }

        public bool DisplayAsNewSection
        {
            get
            {
                return false;
            }
        }
    }
}
